<script setup lang="ts">
import { useRoute } from 'vue-router'
import { ref } from 'vue'
import { vScroll } from '@vueuse/components'
import type { UseScrollReturn } from '@vueuse/core'
import { getGoodsInfo, getOrderList, getViewHistory } from '~/api/index'
import configs from '~/config/index'
import { getTalkDetail, getUserInfo } from '~/pages/template/tools'
import goods from '~/pages/template/goods.vue'
import order from '~/pages/template/order.vue'
import store from '~/pages/template/store.vue'
// 最近浏览 Params
const historySearchParams = ref<any>({
  pageSize: 20,
  pageNumber: 1,
  loading: false,

  total: 0,
})

// 订单 Params
const orderSearchParams = ref<any>({
  pageSize: 20,
  pageNumber: 1,
  loading: false,
  total: 0,
})
const orderRef = ref<any>(null)
const historyRef = ref<any>(null)
const route = useRoute()
const storeRole = ref<any>('')
const goodsData = ref<any>('')
const historyGoodsList = ref<any>([])
const talkDetail = ref<any>('')
const userDetail = ref<any>('')
const orderList = ref<any>([])
const activeTab = ref<any>('consulting')
const extraUserTab = ref<any>([
  {
    label: '正在咨询',
    value: 'consulting',
  },
  {
    label: '我的订单',
    value: 'order',
  },
  {
    label: '店铺信息',
    value: 'storeInfo',
  },
])

function handleChangeTab(item: any) {
  activeTab.value = item.value
}

async function init() {
  storeRole.value = getUserInfo()?.___role === 'STORE'

  if (getUserInfo())
    userDetail.value = getUserInfo()

  if (getTalkDetail())
    talkDetail.value = getTalkDetail()

  if (route.query?.id) {
    if (route.query?.goodsId && route.query?.skuId)
      fetchGoodsInfo(route.query.goodsId, route.query.skuId)
    fetchOrderList()
  }

  // 查询最近浏览
  fetchUserHistory()
}

async function fetchOrderList() {
  orderSearchParams.value.loading = true
  const append = appendParams().params
  const params = {
    pageNumber: orderSearchParams.value.pageNumber,
    pageSize: orderSearchParams.value.pageSize,
    ...append,
  }

  try {
    const res = await getOrderList(params)
    orderSearchParams.value.loading = false
    if (res.data.success)
      orderSearchParams.value.total = res.data.result.total
    orderList.value.push(...res.data.result.records)
  }
  catch (error) {
    orderSearchParams.value.loading = false
  }
}

async function fetchGoodsInfo(goodsId: any, skuId: any) {
  try {
    const res = await getGoodsInfo(goodsId, skuId)
    if (res.data?.success)
      goodsData.value = res.data.result.data
  }
  catch (error) {
    goodsData.value = ''
  }
}

function reachHistoryBottom(state: UseScrollReturn) {
  reachBottom(state, 'history')
}
function reachBottom(state: UseScrollReturn, type: string) {
  const { arrivedState } = state

  // 提取常量以提高代码可读性
  const { bottom } = arrivedState
  const { pageSize, pageNumber, total, loading } = type === 'order' ? orderSearchParams.value : historySearchParams.value
  const isAtBottom = bottom && !loading
  const hasNextPage = pageSize * pageNumber < total

  if (isAtBottom && hasNextPage) {
    const nextPageNumber = pageNumber + 1
    if (type === 'order') {
      orderSearchParams.value.pageNumber = nextPageNumber
      fetchOrderList()
    }
    else {
      historySearchParams.value.pageNumber = nextPageNumber
      fetchUserHistory()
    }
  }
}

// 滚动到底部 加载更多
function reachOrderBottom(state: UseScrollReturn) {
  reachBottom(state, 'order')
}

// 追加params 查询订单以及查询浏览信息都会用到
function appendParams() {
  const client: 'store' | 'buyer' = storeRole.value ? 'store' : 'buyer'
  const appendParams = {
    memberId: '',
    storeId: '',
  }
  if (client === 'store') {
    appendParams.memberId = talkDetail.value.userId
    appendParams.storeId = userDetail.value.id
  }
  else {
    appendParams.memberId = userDetail.value.id
    appendParams.storeId = talkDetail.value.userId
  }
  return { params: appendParams, client }
}

// 查询最近浏览
async function fetchUserHistory() {
  historySearchParams.value.loading = true
  const append = appendParams().params
  const params = {
    pageNumber: historySearchParams.value.pageNumber,
    pageSize: historySearchParams.value.pageSize,
    ...append,
  }
  try {
    const res = await getViewHistory(appendParams().client, params)
    if (res.data.success) {
      // 查询成功
      historyGoodsList.value = res.data.result.records
    }
  }
  catch (error) {
    historySearchParams.value.loading = false
  }
}
onMounted(() => {
  init()
})
</script>

<template>
  <div w-340px overflow-hidden>
    <!-- 用户端额外展示 -->
    <div :style="{ background: configs.GRAYCOLOR }" flex cursor-pointer flex-a-c>
      <div
        v-for="(item, index) in extraUserTab" :key="index" :class="{ active: activeTab === item.value }" h-42px flex
        flex-1 flex-j-c flex-a-c @click="handleChangeTab(item)"
      >
        {{ item.label }}
      </div>
    </div>
    <div v-auto-animate py-16px>
      <div v-if="activeTab === 'consulting'">
        <goods v-if="goodsData" send :res="goodsData" />
        <div v-else text-center text-12px color-warmgray>
          暂无商品信息
        </div>
      </div>

      <div
        v-if="activeTab === 'order'" ref="orderRef" v-scroll="[reachOrderBottom, { throttle: 10 }]"
        class="order-list"
      >
        <order v-for="(item, index) in orderList" :key="index" :res="item" />
      </div>
      <div v-if="activeTab === 'storeInfo'" class="order-list">
        <store />
      </div>
    </div>
    <div>
      <a-tabs v-if="activeTab !== 'order'" class="history" default-active-key="history" lazy-load>
        <a-tab-pane key="history" title="最近浏览">
          <!-- 展示商品信息 -->
          <div ref="historyRef" v-scroll="[reachHistoryBottom, { throttle: 10 }]" class="history-list">
            <goods v-for="(item, index) in historyGoodsList" :key="index" send border-b :res="item" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<style scoped>
.active {
  box-sizing: border-box;
  border-top: 2px solid rgb(var(--arcoblue-6));
  background: #fff;
}

:deep(.arco-tabs-nav-tab) {
  display: flex;
  justify-content: center;
}

:deep(.arco-tabs-content) {
  padding-top: 0;
}

.order-list {
  height: calc(100vh - 155px);
  overflow-y: auto;
}

.history-list {
  height: calc(100vh - 310px) !important;
  overflow-y: auto;
}
</style>
